<?php

class jqueryvalidateJs extends JsPlugin{
    
    private $validation = array();
    private $val_message = array();
    private $masks  = "";
    private $output = "";
    private $formname = "";
    private $reset = "";
    
    public function init() {
        $this->LoadResource("html", "Html");
        $this->LoadJsPlugin('jqueryui/blockui', 'bui');
        $this->Html->LoadJs("$this->url/js/clearform");
        $this->Html->LoadJs("$this->url/js/maskedin");
        $this->Html->LoadJs("$this->url/js/jquery.validate.min");
    }
    
    static private $instance;
    public static function getInstanceOf($plugin){
        $class_name = __CLASS__;
        if (!isset(self::$instance)) {
            self::$instance = new $class_name($plugin);
        }

        return self::$instance;
    }
    
    public function setCurrentForm($form){
        $this->formname = $form;
        $this->formquene[] = $form;
        $this->masks[$form] = "";
        $this->validation[$form] = array();
        $this->val_message[$form] = array();
    }
    
    public function addValidation($field, $validation, $message){
        $this->validation [$this->formname][$field][]  = $validation;
        $this->val_message[$this->formname][$field][]  = $message;
    }
    
    public function addMask($mask){
        $this->masks[$this->formname] .= $mask . " \n\n\t ";
    }
    
    public function addToReset($function){
        $this->reset .= $function;
    }
    
    public function validate($form, $ajax){
        $esp = (DEBUG)?"\n\t\t":"";
        
        $vig = "$esp";
        $this->output .= " ".$this->masks[$form];
        
        if(!empty ($this->validation[$form])){
            $this->output .= " $('#$form').validate({rules:{";
            foreach($this->validation[$form] as $field => $rules){
                $rule = implode(", ", $rules);
                $this->output .= "$vig \"$field\":{ $rule }";
                $vig = ", $esp";
            }
            $vig = "";
            $this->output .= " } , $esp$esp messages:{";
            foreach($this->val_message[$form] as $field => $messages){
                $msg           = implode(", ", $messages);
                $this->output .= "$vig \"$field\":{ $msg }";
                $vig = ", $esp";
            }
            $this->output .= "},$esp
                success: function(label) {
                    $('#v'+label.attr('for')).text('Ok!').removeClass('erro').addClass('valid_msg');
                },$esp
                errorPlacement: function(label, element) {
                    $('#v'+label.attr('for')).text(label.text()).removeClass('valid_msg').addClass('erro'); 
                }";

            $addAjax = "";
            if($ajax){
                $this->output .= "
                    ,submitHandler: function(form) {
                        $.ajax({
                            url: $('#'+form.id).attr('action'),
                            type: 'POST',
                            data: $('#'+form.id).serialize(),
                            dataType: 'json',
                            beforeSend: function(){
                                blockUI_wait(\"Enviando dados...\");
                                $('#erro').hide();
                                $('#success').hide();
                                $('.erro').delay('1200').fadeOut('slow');
                                $('.valid_msg').delay('1200').fadeOut('slow');
                            },
                            success: function(json) {
                                blockUI_unwait();
                                if(typeof json.redirect != 'undefined') {
                                    window.location.href = json.redirect;
                                }

                                if(json.status == 1){
                                    if(json.is_editing != 1){                                    
                                        $('#$form')[0].reset();
                                        $this->reset
                                    }
                                    if (typeof json.success != 'undefined' && json.success != '') blockUI_success(json.success);
                                    else if(typeof json.alert != 'undefined' && json.alert != '') blockUI_alert(json.alert);
                                    else blockUI_error('Operação concluída, mas sem resposta do servidor!');
                                }else{
                                    if (typeof json.erro != 'undefined') blockUI_error(json.erro);
                                    else blockUI_error('Operação concluída, mas sem resposta do servidor!');
                                    for (var camp in json){
                                         $('#v'+camp).text(json[camp]).fadeIn('slow').addClass('erro').removeClass('valid_msg');
                                    }
                                }

                            },
                            error: function(erro){
                                blockUI_unwait();
                                blockUI_error(\"Erro na comunicação com o site\");
                            }

                        });
                    }";
                    $addAjax = "$('<input type=\"hidden\" id=\"ajax\" name=\"ajax\" value=\"true\" />').appendTo('#$form');";
            }

            $this->output .= "}); $addAjax";
        }
        $this->Html->LoadJQueryFunction($this->output);
        
        //reseta as variaveis
        unset($this->validation[$form]);
        unset($this->val_message[$form]);
        unset($this->masks[$form]);
        $this->output = "";
        $this->formname = array_shift($this->formquene);
        $this->reset = "";
    } 

}

?>